package edu.indiana.cs.b534.torrent.impl.message;

import edu.indiana.cs.b534.torrent.TDictionary;
import edu.indiana.cs.b534.torrent.TString;
import edu.indiana.cs.b534.torrent.TorrentException;
import edu.indiana.cs.b534.torrent.message.PeerDictionary;
import edu.indiana.cs.b534.torrent.message.TrackerResponse;
import edu.indiana.cs.b534.torrent.struct.TDictionaryImpl;
import edu.indiana.cs.b534.torrent.struct.TStringImpl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TrackerResponseImpl implements TrackerResponse {
    public static final TString FAILURE_KEY = TStringImpl.newInstance("failure reason");
    public static final TString PEERS_KEY = TStringImpl.newInstance("peers");

    private String failureReason;
    private int interval;
    private List<PeerDictionary> peers = new ArrayList<PeerDictionary>();

    public TrackerResponseImpl(InputStream in) throws IOException, TorrentException {
        TDictionary dictionary = TDictionaryImpl.deserialize(in);
        Map dicMap = dictionary.getDictionary();
        TString failureTString = (TString) dicMap.get(FAILURE_KEY);
        if (failureTString != null) {
            this.failureReason = failureTString.getValue();
            throw new TorrentException("Tracker request fails " + failureReason);
        } else {
            TStringImpl peerInformation = (TStringImpl) dicMap.get(PEERS_KEY);

            char[] chars = peerInformation.getValue().toCharArray();

            for (int i = 0; i < chars.length; i += 6) {
                this.peers.add(new PeerDictionaryImpl(new byte[]{(byte) chars[i], (byte) chars[i + 1],
                        (byte) chars[i + 2], (byte) chars[i + 3], (byte) chars[i + 4], (byte) chars[i + 5]}));
            }
        }
    }

    public String getFailureReason() {
        return failureReason;
    }

    public void setFailureReason(String failureReason) {
        this.failureReason = failureReason;
    }

    public int getInterval() {
        return interval;
    }

    public void setInterval(int interval) {
        this.interval = interval;
    }

    public List<PeerDictionary> getPeers() {
        return peers;
    }

    public void setPeers(List<PeerDictionary> peers) {
        this.peers = peers;
    }


}
